package cn.elwy.rcp.ui.explorer.handler;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;

import cn.elwy.common.exception.RunException;
import cn.elwy.common.util.Assert;
import cn.elwy.rcp.core.model.ui.progress.RunnableAdapter;
import cn.elwy.rcp.ui.dialog.MsgDialog;
import cn.elwy.rcp.ui.explorer.core.ProjectConst;
import cn.elwy.rcp.ui.explorer.editor.PackerEditor;
import cn.elwy.rcp.ui.explorer.editor.PackerEditorInput;
import cn.elwy.rcp.ui.explorer.project.ProjectUtil;

public class OpenBuilderHandler implements IHandler {

  @Override
  public void addHandlerListener(IHandlerListener handlerListener) {
  }

  @Override
  public void dispose() {
  }

  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    Shell shell = HandlerUtil.getActiveShell(event);
    try {
      IProject project = ProjectUtil.getSelectionProject(event);
      Assert.notNull(project, "请选择资源管理器向导的资源");

      PackerEditorInput editorInput = new PackerEditorInput(project.getFile(ProjectConst.PACKER_FILE_NAME));
      editorInput.setName(project.getName());
      IWorkbenchPage workbenchPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
      PackerEditor editorPart = (PackerEditor) workbenchPage.openEditor(editorInput, PackerEditor.ID);
      editorPart.setFocus();
    } catch (Exception e) {
      MsgDialog.open(shell, e);
    }
    return null;
  }

  public RunnableAdapter getAdapterMethod() {
    RunnableAdapter runnableAdapter = new RunnableAdapter() {

      @Override
      public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {

        try {
        } catch (RunException e) {
          throw e;
        } catch (Exception e) {
          throw new RunException("加载资源失败！", e);
        }
      }
    };
    return runnableAdapter;
  }

  @Override
  public boolean isEnabled() {
    return true;
  }

  @Override
  public boolean isHandled() {
    return true;
  }

  @Override
  public void removeHandlerListener(IHandlerListener handlerListener) {
  }

}
